<template>
	<view class="chat-detail">
		<view class="header">
			<text>{{ otherUser.nickname }}</text>
		</view>

		<!-- 添加 scroll-into-view 和 scroll-with-animation 属性 -->
		<scroll-view class="message-list" scroll-y :scroll-into-view="scrollToId" scroll-with-animation
			:scroll-top="scrollTop">
			<view v-for="msg in messages" :key="msg.id"
				:class="['message-item', msg.sender_id === myId ? 'my-msg' : 'other-msg']" :id="'msg-' + msg.id">
				<!-- 显示对方头像 -->
				<image v-if="msg.sender_id !== myId" :src="otherUser.avatar || '/static/default_avatar.png'"
					class="avatar" />

				<!-- 显示本人头像 -->
				<image v-if="msg.sender_id === myId" :src="myAvatar || '/static/default_avatar.png'" class="avatar" />

				<view class="content">
					<text>{{ msg.content }}</text>
				</view>
			</view>
			<!-- 添加一个底部锚点元素 -->
			<view id="bottom-anchor"></view>
		</scroll-view>

		<view class="input-area">
			<input v-model="inputMsg" placeholder="输入消息..." @confirm="sendMessage" />
			<button @click="sendMessage">发送</button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			sessionId: 0,
			otherUserId: 0,
			myId: 0,
			myAvatar: '', // 新增本人头像
			otherUser: {},
			messages: [],
			inputMsg: '',
			lastMsgId: 0,
			page: 1,
			loading: false,
			timer: null,
			scrollToId: '',
			scrollTop: 0,
			lastScrollTop: 0
		}
	},
	// onshow(){
	// 	const myInfo = uni.getStorageSync('my_info');
	// 	console.log(myInfo)
	// 	this.myId = myInfo.id;
	// 	this.renzheng();

	// },
	onLoad(options) {
		this.sessionId = options.session_id;
		this.otherUserId = options.other_user_id;
		const myInfo = uni.getStorageSync('my_info');
		console.log(myInfo)
		this.myId = myInfo.id;
		this.myAvatar = myInfo.avatar; // 从本地存储获取本人头像

		// this.renzheng();
		this.loadOtherUser();
		this.loadMessages();
		this.startPolling();
	},
	onUnload() {
		clearInterval(this.timer);
	},
	methods: {
		//认证查询
		async renzheng() {
			const res = await this.$myRuquest({
				url: '/index/dsnv.activities/get_rz_info?id=' + this.myId
			})
			if (res.data.code != 200) {

				uni.showToast({
					title: '请先进行实名认证',
					duration: 1500,
					icon: 'none'
				})
				// 1秒后再跳转，确保Toast显示完整
				setTimeout(() => {
					uni.navigateTo({
						url: `/pagesA/my/tools/certification?id=` + this.myId
					});
				}, 1000);
			}
			return;

		},
		// 检查聊天次数
		async chat_chance() {
			const res = await this.$myRuquest({
				url: '/index/dsnv.chat/chat_chance?uid=' + this.myId + '&other_id=' + this.otherUserId
			})
			if (res.data.code != 200) {

				uni.showToast({
					title: res.data.info,
					duration: 1500,
					icon: 'none'
				})
				// 1秒后再跳转，确保Toast显示完整
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/my/member'
					});
				}, 1000);
				return false;
			}
			return true;

		},
		async loadOtherUser() {
			const res = await this.$myRuquest({
				url: '/index/dsnv.activities/myinfo2',
				method: 'POST',
				data: { id: this.otherUserId }
			});

			if (res.data.code === 200) {
				this.otherUser = {
					...res.data.data,
					avatar: res.data.data.avatar || '/static/default_avatar.png'
				};
			}
		},
		// 在methods中添加滚动到底部的方法
		scrollToBottom() {
			this.$nextTick(() => {
				// 方法1：使用scroll-into-view
				this.scrollToId = 'bottom-anchor';
				// const query = uni.createSelectorQuery().in(this);
				// query.select('.message-list').boundingClientRect();
				// query.exec((res) => {
				// 	if (res[0]) {
				// 		uni.pageScrollTo({
				// 			scrollTop: res[0].height,
				// 			duration: 300
				// 		});
				// 	}
				// });
			});
		},

		async loadMessages(isPolling = false) {
			if (this.loading) return;
			this.loading = true;

			try {
				const res = await this.$myRuquest({
					url: '/index/dsnv.chat/getMessages',
					method: 'POST',
					data: {
						session_id: this.sessionId,
						user_id: this.myId,
						last_id: isPolling ? this.lastMsgId : 0
					}
				});

				if (res.data.code === 200) {
					if (isPolling) {
						if (res.data.data.length > 0) {
							this.messages = [...this.messages, ...res.data.data];
							this.lastMsgId = res.data.data[res.data.data.length - 1].id;
							this.scrollToBottom(); // 轮询获取新消息后滚动到底部
						}
					} else {
						if (this.page === 1) {
							this.messages = res.data.data;
							this.scrollToBottom(); // 首次加载消息后滚动到底部
						} else {
							this.messages = [...res.data.data, ...this.messages];
						}

						if (this.messages.length > 0) {
							this.lastMsgId = this.messages[this.messages.length - 1].id;
						}
					}
				}
			} catch (e) {
				console.error('加载消息失败:', e);
			} finally {
				this.loading = false;
			}
		},

		async sendMessage() {
			// 1. 先检查实名认证
			await this.renzheng();
			
			// 2. 检查聊天次数（新增await等待检查完成）
			const canChat = await this.chat_chance();
			if (!canChat) return; // 如果次数不足，这里会直接返回
			
			if (!this.inputMsg.trim()) return;

			const res = await this.$myRuquest({
				url: '/index/dsnv.chat/sendMessage',
				method: 'POST',
				data: {
					session_id: this.sessionId,
					sender_id: this.myId,
					content: this.inputMsg
				}
			});

			if (res.data.code === 200) {
				this.inputMsg = '';
				this.loadMessages();
				this.scrollToBottom(); // 发送消息后滚动到底部
			}
		},
		startPolling() {
			this.timer = setInterval(() => {
				this.loadMessages(true); // 传入true表示是轮询请求
			}, 3000);
		},
		loadMore() {
			if (this.loading || this.messages.length === 0) return;

			this.page++;
			this.loadMessages(); // 不传参数，表示是加载更多
		}
	},

	onReady() {
		this.scrollToBottom(); // 页面初次渲染完成后滚动到底部
	}
}
</script>

<style>
/* 新增样式确保头像对齐 */
.my-msg {
	justify-content: flex-end;
}

.my-msg .avatar {
	order: 1;
	/* 本人头像在右侧 */
	margin-left: 20rpx;
}

.other-msg {
	justify-content: flex-start;
}

.other-msg .avatar {
	order: 0;
	/* 对方头像在左侧 */
	margin-right: 20rpx;
	margin-left: 0;
}

.chat-detail {
	display: flex;
	flex-direction: column;
	height: 95vh;
}

.header {
	padding: 20rpx;
	text-align: center;
	font-size: 36rpx;
	font-weight: bold;
	border-bottom: 1rpx solid #eee;
}

/* 确保消息列表有固定高度 */
.message-list {
	flex: 1;
	padding: 20rpx;
	overflow: auto;
	height: calc(100vh - 200rpx);
	box-sizing: border-box;
}

/* 添加底部锚点样式（不可见） */
#bottom-anchor {
	height: 10vh;
	width: 100%;
}

.message-item {
	display: flex;
	margin-bottom: 30rpx;
}

.my-msg {
	justify-content: flex-end;
}

.other-msg {
	justify-content: flex-start;
}

.avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.content {
	max-width: 70%;
	padding: 15rpx 20rpx;
	border-radius: 10rpx;
	background-color: #f5f5f5;
}

.my-msg .content {
	background-color: #08c;
	color: #fff;
}

.input-area {
	display: flex;
	padding: 20rpx;
	border-top: 1rpx solid #eee;
}

.input-area input {
	flex: 1;
	height: 80rpx;
	padding: 0 20rpx;
	border: 1rpx solid #ddd;
	border-radius: 10rpx;
	margin-right: 20rpx;
}

.input-area button {
	width: 150rpx;
	height: 80rpx;
	line-height: 80rpx;
}
</style>